//
//  RatesViewController.m
//  PriceOnline
//
//  Created by Le Anh Tai on 8/11/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "RatesViewController.h"
#import "Utility.h"
#import "UIConstants.h"
#import "RatesCell.h"
#import "SyncHttpRequest.h"
#import "DOMParser.h"
#import "Reachability.h"
#import "UIImage+Color.h"
#import "RootViewControler.h"
#import "Database.h"
#import "Utility.h"

@interface RatesViewController ()

@end

@implementation RatesViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // Custom initialization
        self.title = TEXT_TITLE_EXCHANGE_RATE;
        self.iconImage = @"iconExchangeRate.png";
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _fetchingExchangeRates = NO;

    _preExchangeRatesDic = [[Database sharedInstance] objectForKey:PREV_RATE_KEY];
    _exchangeRatesDic = [[Database sharedInstance] objectForKey:CURR_RATE_KEY];
    
    //refresh button
    UIImage *img = [[UIImage imageNamed:@"btnRefesh.png"] imageWithTint:COLOR_BLUE_IOS7];
    [_refreshButton setImage:img forState:UIControlStateNormal];
    
    //
    _titleLabel.textColor = COLOR_WHITE_NORMAL;
    _titleLabel.backgroundColor = COLOR_BLACK_NORMAL;//COLOR(216, 208, 187, 1);
    
    //
    if (!IS_IPHONE)
    {
        [self fetchExchangeRates];
    }
    
//    _refreshExchangeRatesThreadStatus = ThreadRun;
//    [self refreshExchangeRatesThreadProc];

    _pullToRefreshView = [[PullToRefreshView alloc] initWithScrollView:(UIScrollView *) self.tableView];
    [_pullToRefreshView setDelegate:self];
    [self.tableView addSubview:_pullToRefreshView];
    
    _detailCallOut = [[DetailUpDownRateCallOutView alloc]init];
    _detailCallOut.mainDelegate = self;
    
    _tableView.backgroundColor = COLOR(40, 40, 40, 1);
    
    [self loadLastIndexPath];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (_lastContentOffsetY)
    {
        [UIView animateWithDuration:0.4 animations:^{
            _tableView.contentOffset = CGPointMake(0, _lastContentOffsetY);
        }];
        
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _lastContentOffsetY = _tableView.contentOffset.y;
}

- (void)pullToRefreshViewShouldRefresh:(PullToRefreshView *)view;
{
    [self refreshButtonPress:nil];
    [_pullToRefreshView finishedLoading];
}

- (NSDate*)getCurrentUpdateDate
{
    NSDate *updatedDate = [_exchangeRatesDic objectForKey:KEY_UPDATED_DATE];
    return updatedDate;
}

- (NSDate*)getPreviousUpdateDate
{
    NSDate *preUpdatedDate = [_preExchangeRatesDic objectForKey:KEY_UPDATED_DATE];
    return preUpdatedDate;
}

- (void)loadTheme:(BOOL)isDarkTheme
{
    if (isDarkTheme)
    {
        _titleLabel.textColor = COLOR_WHITE_NORMAL;
        _titleLabel.backgroundColor = COLOR_LIGHT_BLACK;//COLOR(216, 208, 187, 1);
        _headerView.backgroundColor = COLOR_BACKGROUND_HEADER_DARK;//COLOR(77, 77, 77, 1);
        
        NSArray *subviews = _headerView.subviews;
        for (UILabel *label in subviews) {
            if ([label isKindOfClass:[UILabel class]] == NO)
            {
                continue;
            }
            
            label.textColor = COLOR_TEXT_ORANGE_DARK;
        }
        
        _pullToRefreshView.backgroundColor = COLOR_BACKGROUND_PULL_TO_REFRESH_DARK;
    }
    else
    {
        _titleLabel.textColor = COLOR_TEXT_HEADER_LIGHT;
        _titleLabel.backgroundColor = COLOR_WHITE_NORMAL;//COLOR(216, 208, 187, 1);
        _headerView.backgroundColor = COLOR_BACKGROUND_LIGHT;
        
        NSArray *subviews = _headerView.subviews;
        for (UILabel *label in subviews) {
            if ([label isKindOfClass:[UILabel class]] == NO)
            {
                continue;
            }
            
            label.textColor = COLOR_TEXT_ORANGE_LIGHT;
        }
        
        _pullToRefreshView.backgroundColor = COLOR_BACKGROUND_PULL_TO_REFRESH_LIGHT;
    }
}

- (void)reloadLanguage
{
    _typeLabel.text = NSLocalizedString(@"Mã NT", nil);
    _buyLabel.text = NSLocalizedString(@"Mua", nil);
    _ckLabel.text = NSLocalizedString(@"Chuyển khoản", nil);
    _sellLabel.text = NSLocalizedString(@"Bán", nil);
    _unitLabel.text = NSLocalizedString(@"(Đơn vị: Đồng/Ngoại tệ)", nil);
    
    _titleLabel.text = [NSString stringWithFormat:NSLocalizedString(_curUpdateString, nil), [_lastUpdate stringWithFormat:DISPLAY_DATE_FORMAT] ];
}
#pragma mark - Fetch gold price
- (void)fetchExchangeRates
{
    _curUpdateString = @"Đang cập nhật...";
    _titleLabel.text = NSLocalizedString(_curUpdateString, nil) ;
    [self performSelectorInBackground:@selector(performFetchingExchangeRates) withObject:nil];
}

- (void)performFetchingExchangeRates
{
    if (_fetchingExchangeRates == YES)
    {
        return;
    }
    
    //
    _fetchingExchangeRates = YES;
    
    //
    NSDate *updatedDate_old = nil;
    
    if (_exchangeRatesDic)
    {
        updatedDate_old = [_exchangeRatesDic objectForKey:KEY_UPDATED_DATE];
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:VCB_EXCHANGE_RATES_URL]];
    __block NSData *_data = nil;
    
    [SyncHttpRequest connectionWithRequest:request callback:^(NSData *data)
     {
         _data = data;
     }];
    
    if (_data == nil)
    {
        _fetchingExchangeRates = NO;

        [self loadExchangeRatesOffline];

        return;
    }
    
    //
    NSString *xml = [[NSString alloc] initWithBytes:[_data bytes] length:[_data length] encoding:NSUTF8StringEncoding];
    if (xml == nil)
    {
        _fetchingExchangeRates = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    if ([xml hasPrefix:@"<?xml"] == NO)
    {
        _fetchingExchangeRates = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];

        return;
    }
    
    NSArray* exRates = [DOMParser queryXMLNodesByXPath:xml xpath:XPATH_EXCHANGE_RATES_EXRATES namespaceS:nil namespaceNS2:nil];
    if (exRates == nil)
    {
        _fetchingExchangeRates = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];

        return;
    }
    
    NSDate *updateDate = nil;
    NSMutableArray *exchangeRates = [[NSMutableArray alloc] init];
    
    for (NSDictionary *exRate in exRates)
    {
        NSString *nodeName = [exRate objectForKey:KEY_NODE_NAME];
        if (nodeName == nil)
        {
            continue;
        }
        
		#warning Parse DateTime first xpath = "/ExrateList/DateTime"
        if ([nodeName isEqualToString:@"DateTime"])
        {
            NSString *dateTime = [exRate objectForKey:KEY_NODE_CONTENT];
            
            if (dateTime == nil)
            {
            	_fetchingExchangeRates = NO;
                
                [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
                
                return;
            }
            
            updateDate = [NSDate dateWithFormat:EXCHANGE_RATES_UPDATED_DATE_FORMAT AndValue:dateTime];
            if (updateDate == nil)
            {
            	_fetchingExchangeRates = NO;
                
                [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];

                return;
            }
            
            continue;
        }
        
        //
        if ([nodeName isEqualToString:@"Exrate"])
        {
            NSMutableDictionary *attributes = [exRate objectForKey:KEY_NODE_ATTRIBUTE];
            if (attributes == nil)
            {
                continue;
            }

            NSInteger buy = (NSInteger)ceilf([[attributes objectForKey:RATE_BUY_KEY] floatValue]);
            NSInteger ck = (NSInteger)ceilf([[attributes objectForKey:RATE_TRANSFER_KEY]  floatValue]);
            NSInteger sell = (NSInteger)ceilf([[attributes objectForKey:RATE_SELL_KEY]  floatValue]);
            
            [attributes setObject:buy == 0 ? @"" : [Utility stringCurrencyForInteger:buy] forKey:RATE_BUY_KEY];
            [attributes setObject:ck == 0 ? @"" : [Utility stringCurrencyForInteger:ck] forKey:RATE_TRANSFER_KEY];
            [attributes setObject:sell == 0 ? @"" : [Utility stringCurrencyForInteger:sell] forKey:RATE_SELL_KEY];

            if ([[attributes objectForKey:RATE_CODE_KEY] isEqual:@"AUD"] ||
                [[attributes objectForKey:RATE_CODE_KEY] isEqual:@"EUR"] ||
                [[attributes objectForKey:RATE_CODE_KEY] isEqual:@"GBP"] ||
                [[attributes objectForKey:RATE_CODE_KEY] isEqual:@"JPY"] ||
                [[attributes objectForKey:RATE_CODE_KEY] isEqual:@"USD"])
            {
                [exchangeRates insertObject:attributes atIndex:0];
            }
            else
            {
                [exchangeRates addObject:attributes];
            }
            
            continue;
        }
    }
    
    //
    if (_exchangeRatesDic != nil)
    {   
        if ([Utility isDate:updatedDate_old ssGreaterOrEqualDate:updateDate])
        {
            NSLog(@"Do not need to update exchange rates");
            
            _fetchingExchangeRates = NO;
            
            [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
            
            [self performSelectorOnMainThread:@selector(showMessageUpdated:) withObject:NSLocalizedString(@"Tỷ giá đã mới nhất", nil) waitUntilDone:NO];
            
            return;
            
        }
    }
    
    //
    NSMutableDictionary *exchangeRatesDic = [[NSMutableDictionary alloc] init];
    
    if (exchangeRates.count == 0 || updateDate == nil)
    {
        _fetchingExchangeRates = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    if (exchangeRates)
    {
        exchangeRatesDic = [[NSMutableDictionary alloc] init];
        
        [exchangeRatesDic setObject:updateDate forKey:KEY_UPDATED_DATE];
        [exchangeRatesDic setObject:exchangeRates forKey:KEY_EXCHAGE_RATES];
    }
    
    // Sort data as the same way its showed on sjc website
    //    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
    //    [goldPriceDictionary sortUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];
    //    recentSortedArray = [goldPriceDictionary copy];
    
    //
    [self performSelectorOnMainThread:@selector(updateExchangeRates:) withObject:exchangeRatesDic waitUntilDone:NO];
}

- (void)showUpdatedDate:(NSDate *)updatedDate
{
    NSString *text;
    
    if (updatedDate)
    {
        _lastUpdate = updatedDate;
        _curUpdateString = @"Cập nhật lúc: %@";
        text = [NSString stringWithFormat:NSLocalizedString(_curUpdateString, nil), [updatedDate stringWithFormat:DISPLAY_DATE_FORMAT]];
    }
    else
    {
        _lastUpdate = nil;
        _curUpdateString = @"Bị lỗi trong quá trình cập nhật";
        text = NSLocalizedString(_curUpdateString, nil);
    }
    
    _titleLabel.text = text;
}

- (void)loadExchangeRatesOffline
{
    NSLog(@"Load exchangeRates offline");

    if (_exchangeRatesDic)
    {
        [self performSelectorOnMainThread:@selector(updateExchangeRates:) withObject:_exchangeRatesDic waitUntilDone:NO];
    }
    else
    {
        _curUpdateString = @"Chưa có dữ liệu offline";
        _titleLabel.text = NSLocalizedString(_curUpdateString, nil);
    }
}

- (void)showMessageUpdated:(NSString*)string
{
    if (_isPressedRefresh)
    {
        _isPressedRefresh = NO;
        [Utility showInfoMsg:string inView:self.view];

        [self performSelector:@selector(hideLoading) withObject:nil afterDelay:1.5];
    }
}

- (void)updateExchangeRates:(NSMutableDictionary *)exchangeRatesDic
{
    BOOL reloadTable = NO;
    
    if ([_exchangeRatesDic isEqual:exchangeRatesDic])
    {
        reloadTable = YES;
    }
    else
    {
        if (exchangeRatesDic)
        {
            reloadTable = YES;
            
            //
            if (_exchangeRatesDic)
            {
                _preExchangeRatesDic = _exchangeRatesDic;
                [[Database sharedInstance] setObject:_preExchangeRatesDic forKey:PREV_RATE_KEY];
            }
            
            //
            _exchangeRatesDic = exchangeRatesDic;
            [[Database sharedInstance] setObject:_exchangeRatesDic forKey:CURR_RATE_KEY];
            
            [[Database sharedInstance] save];
        }
        else
        {
            assert(0);
        }
    }
    
    [self updateExchangeRatesUI:[_exchangeRatesDic objectForKey:KEY_UPDATED_DATE] reloadTable:reloadTable];
}

- (void)updateExchangeRatesUI:(NSDate *)updatedDate reloadTable:(BOOL)reloadTable
{
    NSLog(@"Update exchange rates");
    
    _fetchingExchangeRates = NO;
    
    if (reloadTable)
    {
        [_tableView reloadData];
    }
    
    [self showUpdatedDate:updatedDate];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    NSInteger paddingRight = 20;
    NSInteger typeWid = (self.view.width - paddingRight)/5;

    _typeLabel.frame = RECT(0, _typeLabel.top, typeWid*2, _typeLabel.height);
    _unitLabel.frame = RECT(0, _unitLabel.top, _typeLabel.width, _unitLabel.height);
    _buyLabel.frame = RECT(_typeLabel.right, _typeLabel.top, typeWid, _buyLabel.height);
    _ckLabel.frame = RECT(_buyLabel.right, _typeLabel.top, typeWid, _ckLabel.height);
    _sellLabel.frame = RECT(_ckLabel.right, _typeLabel.top, self.view.width - _ckLabel.right - paddingRight, _sellLabel.height);
    
    if (_detailCallOut.superview && _selectedIndexPath)
    {
        [self positioningCalloutAtIndexPath:_selectedIndexPath];
    }
}

- (void)saveLastIndexPath
{
    _lastContentOffsetY = _tableView.contentOffset.y;
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:_lastContentOffsetY] forKey:@"LastIndexPathRate"];
}

- (void)loadLastIndexPath
{
    _lastContentOffsetY = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LastIndexPathRate"] integerValue];
}

- (void)viewDidUnload
{
    [self setTitleLabel:nil];
    [self setTypeLabel:nil];
    [self setBuyLabel:nil];
    [self setCkLabel:nil];
    [self setSellLabel:nil];
    [self setTableView:nil];
    [self setUnitLabel:nil];
    [super viewDidUnload];
}

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_exchangeRatesDic == nil)
    {
        return 0;
    }
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_exchangeRatesDic == nil)
    {
        return 0;
    }
    
    NSArray *rates = [_exchangeRatesDic objectForKey:KEY_EXCHAGE_RATES];
    
    return [rates count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    
    static NSString *identifier = @"RatesCell";
    RatesCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil)
    {
        cell = [[RatesCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    NSMutableDictionary *dict = [self getRateDataAtSection:indexPath.section row:row];
    
    [cell loadDataWithDictionary:dict];
    
    if (_selectedIndexPath && _selectedIndexPath.row == indexPath.row && _selectedIndexPath.section == indexPath.section)
    {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self showDataCalloutView];
    }
    
    return cell;
}

- (NSMutableDictionary*)getRateDataAtSection:(NSInteger)section row:(NSInteger)row
{
    //
    NSDictionary *preData = nil;
    NSString *preRateCode = nil;
    
    if (_preExchangeRatesDic)
    {
        NSArray *rates = [_preExchangeRatesDic objectForKey:KEY_EXCHAGE_RATES];
        preData = [Utility getObject:rates atIndex:row];
        
        preRateCode = [preData objectForKey:RATE_CODE_KEY];
    }
    
    //
    NSArray *rates = [_exchangeRatesDic objectForKey:KEY_EXCHAGE_RATES];
    NSDictionary *data = [Utility getObject:rates atIndex:row];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:data];
    
    if (preData && [preRateCode isEqualToString:[data objectForKey:RATE_CODE_KEY]])
    {
        NSString *value = [preData objectForKey:RATE_BUY_KEY];
        if ([Utility isEmptyString:value]) {
            value = @"";
        }
        
        [dict setObject:value forKey:PRE_RATE_BUY_KEY];
        
        
        value = [preData objectForKey:RATE_TRANSFER_KEY];
        if ([Utility isEmptyString:value]) {
            value = @"";
        }
        
        [dict setObject:value forKey:PRE_RATE_TRANSFER_KEY];
        
        
        value = [preData objectForKey:RATE_SELL_KEY];
        if ([Utility isEmptyString:value]) {
            value = @"";
        }
        
        [dict setObject:value forKey:PRE_RATE_SELL_KEY];
    }
    
    return dict;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_selectedIndexPath && _selectedIndexPath.row == indexPath.row && _selectedIndexPath.section == indexPath.section)
    {
        _selectedIndexPath = nil;
        [self removeCalloutView];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        return;
    }
    
    [self addCalloutView];
    [self positioningCalloutAtIndexPath:indexPath];
    _selectedIndexPath = indexPath;
    [self showDataCalloutView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self removeCalloutView];
}

#pragma mark - CALL OUT
- (void)showDataCalloutView
{
    if (_selectedIndexPath == nil)
    {
        return;
    }
    
    NSDictionary *dict = [self getRateDataAtSection:_selectedIndexPath.section row:_selectedIndexPath.row];
    NSString *lastDate = [[self getPreviousUpdateDate] stringWithFormat:DISPLAY_DATE_FORMAT_SHORT];
    NSString *curDate = [[self getCurrentUpdateDate] stringWithFormat:DISPLAY_DATE_FORMAT_SHORT];
    [_detailCallOut loadDataWithRateDictionary:dict lastDate:lastDate currentDate:curDate];
}

- (void)detailUpDownRateCalloutViewouchOutSide:(CalloutView *)view atPoint:(CGPoint)point
{
    CGPoint convertPoint = [self.view convertPoint:point fromView:view];
    if ( CGRectContainsPoint(self.tableView.frame, convertPoint) )
    {
        return;
    }
    
    if (_selectedIndexPath)
    {
        _selectedIndexPath = nil;
        [_tableView selectRowAtIndexPath:nil animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self removeCalloutView];
    }
}

- (CGRect)detailUpDownRateCalloutViewRectForSelectedIndex:(CalloutView *)view
{
    if (_selectedIndexPath == nil || [_tableView cellForRowAtIndexPath:_selectedIndexPath] == nil)
    {
        return CGRectZero;
    }
    
    return [[DataSingleton shared].rootViewController.view convertRect:[_tableView rectForRowAtIndexPath:_selectedIndexPath] fromView:_tableView];
}

- (void)removeCalloutView
{
    if (_detailCallOut && _detailCallOut.superview)
    {
        [_detailCallOut removeFromSuperview];
    }
}

- (void)addCalloutView
{
    if (!_detailCallOut.superview)
    {
        [[DataSingleton shared].rootViewController.view addSubview:_detailCallOut];
        
        _detailCallOut.alpha = 0;
        
        [UIView animateWithDuration:0.4 animations:^{
            _detailCallOut.alpha = 1;
        }];
    }
}

- (void)positioningCalloutAtIndexPath:(NSIndexPath*)indexPath
{
    CGRect rect = [_tableView rectForRowAtIndexPath:indexPath];
    rect.origin = [[DataSingleton shared].rootViewController.view convertPoint:rect.origin fromView:_tableView];
    
    CGRect calloutRect;
    
    calloutRect.size.width = self.view.width;
    calloutRect.size.height = 115;
    calloutRect.origin.x = rect.origin.x;
    calloutRect.origin.y = rect.origin.y - calloutRect.size.height;
    
    [_detailCallOut setFrame:RECT(calloutRect.origin.x, calloutRect.origin.y, calloutRect.size.width, calloutRect.size.height)];
}

- (void)deactive
{
    _refreshExchangeRatesThreadStatus = ThreadPause;
}

- (void)active
{
    _refreshExchangeRatesThreadStatus = ThreadRun;
    [self fetchExchangeRates];
}

//#pragma mark - Refresh Gold Price Thread
//- (void)refreshExchangeRatesThreadProc
//{
//    dispatch_queue_t _refreshExchangeRatesThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    
//    dispatch_async(_refreshExchangeRatesThread, ^{
//        while (_refreshExchangeRatesThreadStatus != ThreadStop)
//        {
//            if (_refreshExchangeRatesThreadStatus == ThreadPause)
//            {
//                [NSThread sleepForTimeInterval:5.0f];
//                NSLog(@"Pause update exchange rates");
//
//                continue;
//            }
//            
//            [NSThread sleepForTimeInterval:UPDATE_RATE_PRICE_INTERVAL];
//            
//            [self performFetchingExchangeRates];
//        }
//    });
//}

- (void)hideLoading
{
    [Utility hideLoading:self.view];
}

- (IBAction)refreshButtonPress:(id)sender
{
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable)
    {
        [Utility showLoading:self.view withMsg:NSLocalizedString(@"Chưa kết nối mạng", nil)];
        [self performSelector:@selector(hideLoading) withObject:nil afterDelay:1.5];
    }
    else
    {
        _isPressedRefresh = YES;
        [self fetchExchangeRates];
    }
    
}

- (void)dealloc
{
    _refreshExchangeRatesThreadStatus = ThreadStop;
    
    [_exchangeRatesDic removeAllObjects];
    _exchangeRatesDic = nil;
}

@end
